package com.mz.mattress.api.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class RedisClient {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public static final String LUA_RANGE_GET_REM = "local dataSet=redis.call('ZRANGEBYSCORE',KEYS[1],KEYS[2],KEYS[3]) redis.call('ZREMRANGEBYSCORE',KEYS[1],KEYS[2],KEYS[3]) return dataSet";

    public List<Integer> rangeAndRemoveByScore(String key, long min, long max) {

        DefaultRedisScript<List> script = new DefaultRedisScript<>(LUA_RANGE_GET_REM, List.class);

        List<String> keyList = new ArrayList<>();
        keyList.add(key);
        keyList.add(min + "");
        keyList.add(max + "");

        List<String> argList = new ArrayList<>();

        List list = redisTemplate.execute(script, keyList, argList);// 执行脚本并获取结

        if (list == null || list.size() == 0) {
            return null;
        }

        List<Integer> arrayList = new ArrayList<>(list.size());
        for (Object object : list) {
            arrayList.add((Integer) object);
        }

        return arrayList;

    }

}
